package com.stedu.mall.adminService.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.stedu.mall.adminService.mapper.AdminMapper;
import com.stedu.mall.common.bean.Admin;
import com.stedu.mall.common.exception.SteduException;
import com.stedu.mall.common.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Override
    public Admin login(String username, String password) throws SteduException {
        Admin admin = adminMapper.selectByUsername(username);
        if(admin == null){
            throw new SteduException("用户名错误");
        }

        String md5Pwd = SecureUtil.md5(SecureUtil.md5(password+admin.getSalt()));

        if(!md5Pwd.equals(admin.getPassword())){
            throw new SteduException("密码错误");
        }
        if (admin.getStatus() == 1) {
            throw new SteduException("该用户已被禁用,请联系超级管理员");
        }
        return admin;
    }

    @Override
    public Admin selectById(Integer id) {
        return  adminMapper.selectById(id);
    }

    @Override
    public boolean update(Admin admin) {
        return adminMapper.update(admin) == 1;
    }

    @Override
    public boolean chgPwd(String oldPwd, String newPwd, Integer id) throws SteduException {
        //判断原密码是否正确
        //1.根据id查询用户信息，获取原密码和盐
        Admin admin = adminMapper.selectById(id);
        String salt = admin.getSalt();
        //2.使用用户输入的原密码和盐加密 ->加密之后的用户输入的密码
        String md5InputOldPwd = SecureUtil.md5(SecureUtil.md5(oldPwd + salt));
        //3.和数据库中的原密码比较
        if(!admin.getPassword().equals(md5InputOldPwd)){
            throw new SteduException("原密码输入错误，请确认后重新输入");
        }
        //对新密码结合盐进行加密
        String md5NewPwd = SecureUtil.md5(SecureUtil.md5(newPwd + salt));
        //修改密码
        admin = new Admin();
        admin.setId(id);
        admin.setPassword(md5NewPwd);
        return adminMapper.update(admin) == 1;
    }

    @Override
    public List<Admin> selectAll(Integer status) {
        return adminMapper.selectAll(status);
    }

    @Override
    public boolean delete(Integer id) {
        return adminMapper.delete(id) == 1;
    }

    @Override
    public boolean insert(Admin admin) throws SteduException {
        if (adminMapper.selectByUsername(admin.getUsername()) != null) {
            throw new SteduException("该管理员已存在,无法添加");
        }
        String salt = RandomUtil.randomString(7);
        String password = SecureUtil.md5(SecureUtil.md5("123" + salt));
        admin.setPassword(password);
        admin.setSalt(salt);
        admin.setStatus(0);
        admin.setCreateTime(new Timestamp(System.currentTimeMillis()));
        return adminMapper.insert(admin) == 1;
    }
}
